/**
 * @ Author: luoqi
 * @ Create Time: 2024-04-01 23:04
 * @ Modified by: luoqi
 * @ Modified time: 2024-04-02 22:59
 * @ Description:
 */

#include "jy901.h"

int jy901_init(JY901Obj *obj)
{
    obj->acc_x = 0;
    obj->acc_y = 0;
    obj->acc_z = 0;
    obj->w_x = 0;
    obj->w_y = 0;
    obj->w_z = 0;
    obj->agl_x = 0;
    obj->agl_y = 0;
    obj->agl_z = 0;
    obj->temperature = 0;
    obj->issof = 0;
    obj->recvcnt = 0;
    return 0;
}

int jy901_decode(JY901Obj *obj, uint8_t *data, int size)
{
    for(int i = 0; i < size; i++) {
        if(data[i] == 0x55) {
            obj->issof = 1;
            obj->data[i] = 0x55;
            obj->recvcnt++;
        }
        if(obj->issof == 1) {
            obj->data[i] = data[i];
            obj->recvcnt++;
        }
        if(obj->recvcnt == 11) {
            obj->issof = 0;
            obj->recvcnt = 0;
            uint8_t sum = 0;
            for(int i = 0; i < 10; i++) {
                sum += obj->data[i];
            }
            if(sum != obj->data[10]) {
                return -1;
            }
            if(obj->data[1] == 0x51) {
                obj->acc_x = (float)((obj->data[3] << 8) | obj->data[2]) / 32768.0 * 9.8;
                obj->acc_y = (float)((obj->data[5] << 8) | obj->data[4]) / 32768.0 * 9.8;
                obj->acc_z = (float)((obj->data[7] << 8) | obj->data[6]) / 32768.0 * 9.8;
                obj->temperature = (float)((obj->data[9] << 8) | obj->data[8]) / 100;

            } else if(obj->data[1] == 0x52) {
                obj->w_x = (float)((obj->data[3] << 8) | obj->data[2]) / 32768.0 * 2000;
                obj->w_y = (float)((obj->data[5] << 8) | obj->data[4]) / 32768.0 * 2000;
                obj->w_z = (float)((obj->data[7] << 8) | obj->data[6]) / 32768.0 * 2000;
                obj->temperature = (float)((obj->data[9] << 8) | obj->data[8]) / 100;
            } else if(obj->data[1] == 0x53) {
                obj->agl_x = (float)((obj->data[3] << 8) | obj->data[2]) / 32768.0 * 180;
                obj->agl_y = (float)((obj->data[5] << 8) | obj->data[4]) / 32768.0 * 180;
                obj->agl_z = (float)((obj->data[7] << 8) | obj->data[6]) / 32768.0 * 180;
                obj->temperature = (float)((obj->data[9] << 8) | obj->data[8]) / 100;
            } else {
                return -1;
            }
            return 11;
        }
    }
    return 0;
}
